package com.example.tasks

import com.google.gson.Gson
import java.io.BufferedInputStream
import java.io.File
import java.util.concurrent.TimeUnit

fun main(args: Array<String>) {
    val rootPath = args[0]
    println(rootPath)
    val mappingFiles = ArrayList<File>(2)
    val jsonFiles = ArrayList<File>(2)
    getMappings(File(rootPath), mappingFiles, jsonFiles)

    jsonFiles.forEach { file ->
        val content = file.readText()
        val data = Gson().fromJson(content, BuildInfo::class.java)
        mappingFiles.find {
            it.absolutePath.contains(data.variantName)
        }?.let {
            test(data.elements[0].versionName, data.variantName, it.absolutePath)
        }
    }
}

fun test(versionName: String, channelName: String, mapping: String) {
    val channel = if (channelName.endsWith("Release")) {
        channelName.substring(0, channelName.length - 7)
    } else channelName
    val cmd =
        "buglySymbolAndroid.bat -u -id 7b938c7d62 -key d8c5e38e-bc82-44e3-8ab0-2ea4cb45f9c9 -package com.arcsoft.perfect365 -version $versionName -channel $channel -mapping $mapping"
    println(cmd)
    val exec = Runtime.getRuntime().exec(cmd)

    exec.waitFor(10, TimeUnit.SECONDS)
    BufferedInputStream(exec.inputStream, 1024).use { stream ->
        val buffer = ByteArray(stream.available())
        var len = 0;
        while ((stream.read(buffer, 0, buffer.size).also {
                len = it
            }) != -1) {
            val consent = String(buffer, 0, len)
            print(consent)
            if (consent.endsWith(". . . ")) break
        }
    }

    println("...upload mapping success...")
}

fun getMappings(path: File, mappingArray: ArrayList<File>, jsonFiles: ArrayList<File>) {
    if (path.isFile) {
        if (path.name == "mapping.txt") mappingArray.add(path)
        else if (path.name == "output-metadata.json") jsonFiles.add(path)
    } else {
        path.listFiles().forEach {
            getMappings(it, mappingArray, jsonFiles)
        }
    }
}

data class BuildInfo(
    val applicationId: String = "",
    val variantName: String = "",
    val elements: Array<ApkInfo> = emptyArray()
) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as BuildInfo

        if (applicationId != other.applicationId) return false
        if (variantName != other.variantName) return false
        if (!elements.contentEquals(other.elements)) return false

        return true
    }

    override fun hashCode(): Int {
        var result = applicationId.hashCode()
        result = 31 * result + variantName.hashCode()
        result = 31 * result + elements.contentHashCode()
        return result
    }

}

data class ApkInfo(val versionCode: Int, val versionName: String)